#import "TeacherViewController.h"
#import "SMViewController.h"
#import "CellStyleTeacher.h"
#import "SDWebImageManager.h"
#import "RegLoginViewController.h"
#import "LogInOutManager.h"
#import "UserInfo.h"
#import "UserDao.h"
#import "ImageUtil.h"
#import "UIImageView+WebCache.h"
#import "UIViewExt.h"
#import "ModifyNameViewController.h"
#import "PhoneRegisterViewController.h"
#import "ModifyPasswordViewController.h"
#import "CameraGalleryManager.h"
#import "MyPostsViewController.h"
#import "AFAppClient.h"
#import "RegLoginViewController.h"
#import "MainViewCreater.h"

@interface TeacherViewController ()<
    UIActionSheetDelegate,
    UINavigationControllerDelegate,
    UIImagePickerControllerDelegate
>
@end

@implementation TeacherViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
    _itemTableView.delegate = self;
    _itemTableView.dataSource = self;
    
    _logout_button.layer.cornerRadius = 5;
    
    _headView = [[UIImageView alloc] initWithFrame:CGRectMake((APP_SCREEN_WIDTH - 74) / 2, 64, 74, 74)];
    _headView.backgroundColor =[UIColor whiteColor];
    _headView.layer.cornerRadius = 37.0f;
    _headView.layer.masksToBounds = YES;
    _headView.userInteractionEnabled = YES;
    [self.view insertSubview:_headView belowSubview:self.cameraIcon];
    self.userIcon.hidden = YES;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(changeHead)];
    [_headView addGestureRecognizer:tap];
    
    _leftButton = [[UIButton alloc] initWithFrame:CGRectMake(7.5, 20, 44, 44)];
    [_leftButton setImage:[UIImage imageNamed:@"nav_btn_back"] forState:UIControlStateNormal];
    _leftButton.backgroundColor = [UIColor clearColor];
    [_leftButton addTarget:self action:@selector(backButton:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_leftButton];
    UIBarButtonItem *backButton = [[UIBarButtonItem alloc]
                                   initWithTitle:@""
                                   style:UIBarButtonItemStylePlain
                                   target:nil
                                   action:nil];
    self.navigationItem.backBarButtonItem=backButton;
    self.view.backgroundColor = DefaultViewBackgroundColor;
    _itemTableView.backgroundColor= DefaultViewBackgroundColor;
    _itemTableView.alwaysBounceVertical = NO;
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    if ([self.itemTableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.itemTableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.itemTableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.itemTableView setLayoutMargins:UIEdgeInsetsZero];
    }
}
- (void)viewWillAppear:(BOOL)animated {

    [super viewWillAppear:animated];
    
    [self.navigationController setNavigationBarHidden:YES animated:YES];
    
    [self refreshData];
}

- (UIStatusBarStyle)preferredStatusBarStyle
{
    return UIStatusBarStyleLightContent;
}

- (IBAction)logoutClick:(id)sender {
    [self logout];
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;
    static NSString *CellIdentifier = @"CellStyleTeacher";
    
    CellStyleTeacher *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        NSArray *nibArr = [[NSBundle mainBundle]loadNibNamed:@"CellStyleTeacher" owner:self options:nil];
        cell = (CellStyleTeacher *)[nibArr objectAtIndex:0];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        switch (section) {
            case 0:
                if (row == 0) {
                    cell.title.text = @"姓名";
                    cell.info.text = [[UserDao getInstance] getUserInfo].nickName;
                }
                break;
            case 1:
                if (row == 0) {
                    cell.title.text = @"更改手机绑定";
                    cell.info.text = [[UserDao getInstance] getUserInfo].phone;
                }else if (row == 1){
                    cell.title.text = @"修改密码";
                    cell.info.text = @" ";
                }
                break;
            case 2:
                if (row == 0) {
                    cell.title.text = @"我的帖子";
                    cell.info.text = @" ";
                }
                break;
            default:
                break;
        }
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    NSInteger section = indexPath.section;
    NSInteger row = indexPath.row;

    if (section == 0 && row == 0) {//修改姓名
        
        [self changeName];
    }else if (section == 1 && row == 0) {//绑定手机
        
        [self changePhone];
    }else if (section == 1 && row == 1) {//修改密码
    
        [self changePassword];
    }else if (section == 2 && row == 0) {//我的帖子
    
        [self openMyPosts];
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0 || section == 2) {
        return 1;
    }
    return 2;
}

//设置Cell行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 50;
}

//设置头高
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return CGFLOAT_MIN;
}

- (void)backButton:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Private Methods

- (void)refreshData {
    
    self.userName.text = [[UserDao getInstance] getUserInfo].nickName;
    [_itemTableView reloadData];
    
    [_headView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",AVATAR_HEADER,[[UserDao getInstance] getUserInfo].avatar]] placeholderImage:[UIImage imageNamed:@"default_circle_icon"]];
}

- (BOOL)checkCamera {
    BOOL isCamera = [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
    if(!isCamera) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"此设备没有摄像头" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [alert show];
        return NO;
    }else{
        return YES;
    }
}

#pragma mark - UIActionSheetDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
//    UIImagePickerControllerSourceType sourceType;
    if(buttonIndex == 0) {
        if([self checkCamera]){
//            sourceType = UIImagePickerControllerSourceTypeCamera;
//            [self openGallery:sourceType];
            [[CameraGalleryManager getInstanse] takePhoto:self finishBlock:^(UIImage *img, NSString * avaURL) {
                if (img) {
                    _headView.image = img;
                    NSDictionary *param = @{@"utype":@(1),@"uid":@([[UserDao getInstance]getUserId]),@"image.jpg":img,@"message":USER_POST_AVATAR};
                    [[AFAppClient sharedManager]postWithURL:SERVER_URL withParameters:param success:^(NSDictionary *responseObject) {
                        if([[responseObject objectForKey:@"retCode"] integerValue]== 1){
                            debugLog(@"retCode:%@",[responseObject objectForKey:@"avatar"]);
                            debugLog(@"retCode:%@",[responseObject objectForKey:@"avatar_header"]);
                            NSString *avatar_url = [responseObject objectForKey:@"avatar"];
                            [[UserDao getInstance]updateUserInfo:@{@"avatar":avatar_url} withReload:YES];
                        }
                    } failure:^(NSError *error) {
                        
                    }];
                }
            }];
        }else{
            return;
        }
    }else if(buttonIndex == 1){
//        sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//        [self openGallery:sourceType];
        [[CameraGalleryManager getInstanse] gallerySelect:self finishBlock:^(UIImage *img, NSString * avaURL) {
            if (img) {
                _headView.image = img;
                NSDictionary *param = @{@"utype":@(1),@"uid":@([[UserDao getInstance]getUserId]),@"image.jpg":img,@"message":USER_POST_AVATAR};
                [[AFAppClient sharedManager]postWithURL:SERVER_URL withParameters:param success:^(id responseObject) {
                    if([[responseObject objectForKey:@"retCode"] integerValue]== 1){
                        debugLog(@"retCode:%@",[responseObject objectForKey:@"avatar"]);
                        debugLog(@"retCode:%@",[responseObject objectForKey:@"avatar_header"]);
                        NSString *avatar_url = [responseObject objectForKey:@"avatar"];
                        [[UserDao getInstance]updateUserInfo:@{@"avatar":avatar_url} withReload:YES];
                    }
                } failure:^(NSError *error) {
                    
                }];

            }
        }];
    }
}

-(void)openGallery:(UIImagePickerControllerSourceType) source{
    //初始化类
    UIImagePickerController *pick = [[UIImagePickerController alloc] init];
    //指定图片来源
    pick.sourceType = source;
    //表示用户可编辑图片。
    pick.allowsEditing = YES;
    //代理
    pick.delegate = self;
    [self presentViewController:pick animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController: (UIImagePickerController *)picker didFinishPickingMediaWithInfo: (NSDictionary *)info {
    
    UIImage *image = [info objectForKey: @"UIImagePickerControllerEditedImage"];
    NSLog(@"%@", image);
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void) imagePickerControllerDidCancel: (UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - Action

- (void)changeHead {

    UIActionSheet *menu = [[UIActionSheet alloc]
                           initWithTitle: @""
                           delegate:self
                           cancelButtonTitle:@"取消"
                           destructiveButtonTitle:nil
                           otherButtonTitles:@"拍照",@"图库相册", nil];
    menu.tag = 1000;
    [menu showInView:self.view];
}

- (void)changeName {

    ModifyNameViewController *view = [[ModifyNameViewController alloc] init];
    view.title = @"修改名称";
    [self.navigationController pushViewController:view animated:YES];
}

- (void)changePhone {

    PhoneRegisterViewController *phone = [[PhoneRegisterViewController alloc] init];
    phone.title = @"修改手机号";
    phone.isRegister = NO;
    [self.navigationController pushViewController:phone animated:YES];
    
}

- (void)changePassword {

    ModifyPasswordViewController *view = [[ModifyPasswordViewController alloc] init];
    view.title = @"修改密码";
    [self.navigationController pushViewController:view animated:YES];
}

- (void)openMyPosts {

    MyPostsViewController *myPost = [[MyPostsViewController alloc] init];
    myPost.title = @"我的帖子";
    [self.navigationController pushViewController:myPost animated:YES];
}

- (void)logout {
    
    NSDictionary *dic = @{@"haslogin":@"0"};
    [[UserDao getInstance] updateUserInfo:dic withReload:YES];
    [[UserDao getInstance] getUserInfo].hasLogin = 0;
    [[UserDao getInstance] getUserInfo].userId = 0;
    [[SMViewController sharedSMViewController]closeSideBar:NO];
    //[[SMViewController sharedSMViewController] backToRegLoginViewController];
    [self dismissViewControllerAnimated:NO completion:nil];
    [[MainViewCreater getInstance]destoryMain];
    RegLoginViewController *reg = [[RegLoginViewController alloc]init];
    UINavigationController *nav = [[UINavigationController alloc]initWithRootViewController:reg];
    UIWindow *window = [[UIApplication sharedApplication]keyWindow];
    window.rootViewController = nav;
}

@end
